<template>
  <div>
    <!-- 加载指示器 -->
    <div v-if="!post.title">加载中...</div>
    
    <!-- 帖子详情内容 -->
    <div v-else class="post-detail">
      <button class="back-button" @click="goBack">
        <i class="fas fa-arrow-left"></i> 返回
      </button>
      
      <div class="post-content-container">
        <h1>{{ post.title }}</h1>
        <p>作者：{{ post.author }}</p>
        <p>日期：{{ formatDate(post.date) }}</p>
        <div class="post-content">
          {{ post.content }}
        </div>
        <div class="post-footer">
          <button @click="likePost" class="like-button">
            <i class="fas fa-heart" :class="{ 'liked': isLiked }"></i>
            <span><svg t="1744449391940" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2496" width="20" height="20"><path d="M512 901.746939c-13.583673 0-26.122449-4.179592-37.093878-13.061225-8.881633-7.314286-225.697959-175.020408-312.424489-311.379592C133.746939 532.37551 94.040816 471.24898 94.040816 384.522449c0-144.718367 108.146939-262.269388 240.326531-262.269388 67.395918 0 131.657143 30.82449 177.632653 84.636735 45.453061-54.334694 109.191837-84.636735 177.110204-84.636735 132.702041 0 240.326531 117.55102 240.326531 262.269388 0 85.159184-37.093878 143.673469-67.395919 191.216327l-1.044898 1.567346c-86.726531 136.359184-303.542857 304.587755-312.424489 311.379592-10.44898 8.359184-22.987755 13.061224-36.571429 13.061225z" fill="#E5404F" p-id="2497"></path></svg>{{ post.likes }}</span>
          </button>
          <span>评论：{{ post.comments?.length || 0 }}</span> <!-- 使用可选链和默认值 -->
          <button v-if="isAuthor" @click="deletePost" class="delete-button">
            <i class="fas fa-trash"></i> 删除帖子
          </button>
        </div>
        
        <div class="comments-section">
          <h3>评论（{{ post.comments?.length || 0 }}）</h3> <!-- 使用可选链和默认值 -->
          
          <!-- 评论列表 -->
          <div v-for="comment in post.comments" :key="comment.id" class="comment-item">
            <p class="comment-author">{{ comment.author }}</p>
            <p class="comment-date">{{ formatDate(comment.date) }}</p>
            <p class="comment-content">{{ comment.content }}</p>
          </div>

          <!-- 评论输入框（登录用户可见） -->
          <div v-if="currentUser" class="new-comment">
            <textarea 
              v-model="newComment" 
              placeholder="写下你的评论..."
              rows="4"
            ></textarea>
            <button @click="submitComment" class="submit-comment-btn">
              <i class="fas fa-paper-plane"></i> 发布
            </button>
          </div>

          <!-- 未登录提示 -->
          <div v-else class="login-prompt">
            <p>请 <router-link to="/login">登录</router-link> 后发表评论</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const route = useRoute();
const router = useRouter();
const post = ref({
  title: '',
  author: '',
  date: '',
  content: '',
  likes: 0,
  comments: [] 
});
const currentUser = ref(null);
const newComment = ref('');
const isLiked = ref(false);

const loadPost = async () => {
  try {
    const response = await fetch(`http://localhost:3000/posts/${route.params.postId}`);
    if (!response.ok) {
      router.push('/not-found');
      return;
    }
    const postData = await response.json();
    
    // 获取评论
    const commentsResponse = await fetch(`http://localhost:3000/posts/${route.params.postId}/comments`);
    post.value = {
      ...postData,
      comments: (await commentsResponse.json()) || [] 
    };
    // 获取当前用户信息
    const token = localStorage.getItem('token');
    if (token) {
      const userResponse = await fetch('http://localhost:3000/profile', {
        headers: {
          'Authorization': token
        }
      });
      if (userResponse.ok) {
        currentUser.value = await userResponse.json();
        
        // 检查是否已点赞
        const likeCheckResponse = await fetch(`http://localhost:3000/posts/${route.params.postId}/like`, {
          method: 'GET',
          headers: { 'Authorization': token }
        });
        isLiked.value = (await likeCheckResponse.json()).liked;
      }
    }
  } catch (error) {
    console.error('加载帖子失败:', error);
    router.push('/not-found');
  }
};

// 计算属性，检查当前用户是否是帖子的作者
const isAuthor = computed(() => {
  return currentUser.value && currentUser.value.username === post.value.author;
});

// 点赞功能
const likePost = async () => {
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      router.push('/login');
      return;
    }
    
    const method = isLiked.value ? 'DELETE' : 'POST';
    const response = await fetch(`http://localhost:3000/posts/${route.params.postId}/like`, {
      method,
      headers: {
        'Authorization': token,
        'Content-Type': 'application/json'
      }
    });
    
    if (response.ok) {
      const result = await response.json();
      post.value.likes = result.newLikes;
      isLiked.value = !isLiked.value;
    } else {
      const errorData = await response.json();
      throw new Error(errorData.error || '点赞操作失败');
    }
  } catch (error) {
    console.error('点赞失败:', error);
    alert(error.message || '点赞失败，请重试');
  }
};

// 提交评论
const submitComment = async () => {
  if (!newComment.value.trim()) {
    alert('评论内容不能为空');
    return;
  }
  
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      router.push('/login');
      return;
    }
    
    const response = await fetch(`http://localhost:3000/posts/${route.params.postId}/comments`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': token
      },
      body: JSON.stringify({ content: newComment.value })
    });
    
    if (response.ok) {
      newComment.value = '';
      // 重新加载评论
      const commentsResponse = await fetch(`http://localhost:3000/posts/${route.params.postId}/comments`);
      post.value.comments = await commentsResponse.json();
    } else {
      throw new Error('评论提交失败');
    }
  } catch (error) {
    console.error('提交评论失败:', error);
    alert('提交评论失败，请重试');
  }
};

// 删除帖子
const deletePost = async () => {
  if (!confirm('确定要删除这个帖子吗？此操作不可撤销。')) {
    return;
  }
  
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      router.push('/login');
      return;
    }
    
    const response = await fetch(`http://localhost:3000/posts/${route.params.postId}`, {
      method: 'DELETE',
      headers: {
        'Authorization': token
      }
    });
    
    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.error || '删除帖子失败');
    }
    
    // 删除成功后跳转回论坛页面
    router.push('/forum');
  } catch (error) {
    console.error('删除帖子失败:', error);
    alert(error.message || '删除帖子失败，请重试');
  }
};

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString);
  return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
};

const goBack = () => {
  router.push('/forum');
};

onMounted(() => {
  loadPost();
});
</script>

<style scoped>
.post-detail {
    background-color: #fffaf5; /* 柔和的米白色背景 */
    min-height: 100vh;
    padding: 2rem;
    font-family: 'Helvetica Neue', Arial, sans-serif;
}

.delete-button {
  background: #f8d7da;
  color: #721c24;
  border: none;
  border-radius: 4px;
  padding: 0.5rem 1rem;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-left: auto;
}

.delete-button:hover {
  background: #f1b0b7;
}

.post-footer {
  display: flex;
  gap: 1.5rem;
  align-items: center;
  margin-top: 2rem;
  padding-top: 1.5rem;
  border-top: 2px solid #f0e2d4;
}

.back-button {
    background: #f5e6d3; /* 浅米色按钮背景 */
    color: #6d4c3d; /* 深棕色文字 */
    border: 1px solid #e0d1c1;
    border-radius: 20px;
    padding: 0.5rem 1.5rem;
    cursor: pointer;
    transition: all 0.3s ease;
    margin-bottom: 1.5rem;
    box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.back-button:hover {
    background: #e8d5c4; /* 稍深的米色 */
    transform: translateY(-1px);
}

.post-content-container {
    max-width: 800px;
    margin: 0 auto;
    background: white;
    border-radius: 15px;
    padding: 2.5rem;
    box-shadow: 0 4px 12px rgba(0,0,0,0.08);
}

h1 {
    color: #5a4132; /* 温暖的咖啡色 */
    font-size: 2.2rem;
    margin-bottom: 1.2rem;
    border-bottom: 2px solid #f0e2d4;
    padding-bottom: 1rem;
}

p {
    color: #7f6b5e; /* 柔和的灰褐色 */
    margin-bottom: 0.8rem;
    font-size: 0.95rem;
}

.post-content {
    color: #635347;
    line-height: 1.8;
    font-size: 1.05rem;
    margin: 2rem 0;
    white-space: pre-line; /* 保留换行格式 */
    padding: 1.5rem;
    background: #fbf7f2; /* 极浅米色内容背景 */
    border-radius: 10px;
}

.post-footer {
    margin-top: 2rem;
    padding-top: 1.5rem;
    border-top: 2px solid #f0e2d4;
    display: flex;
    gap: 1.5rem;
}

.post-footer span {
    color: #8c7465;
    display: flex;
    align-items: center;
    gap: 0.5rem;
    font-size: 0.9rem;
}

.post-footer i {
    color: #d4a88c; /* 柔和的珊瑚色图标 */
}

/* 评论区域样式 */
.comments-section {
  margin-top: 2.5rem;
  padding: 1.5rem;
  background: #fbf7f2;
  border-radius: 10px;
}

.comment-item {
  margin-bottom: 1.5rem;
  padding: 1rem;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.comment-author {
  color: #5a4132;
  font-weight: bold;
}

.comment-date {
  color: #9c8a7d;
  font-size: 0.85rem;
}

.new-comment {
  margin-top: 1.5rem;
}

.new-comment textarea {
  width: 100%;
  padding: 0.8rem;
  border: 2px solid #f0e2d4;
  border-radius: 8px;
  margin-bottom: 0.5rem;
}

.submit-comment-btn {
  background: #f5e6d3;
  color: #6d4c3d;
  border: none;
  padding: 0.6rem 1.2rem;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.submit-comment-btn:hover {
  background: #e8d5c4;
}

/* 点赞按钮样式 */
.like-button {
  background: #fff0f5;
  color: #6200ea;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.like-button.liked {
  background: #ffd7e6;
  color: #ff1493;
}

.like-button:hover {
  background: #ffe6f2;
}

@media (max-width: 768px) {
    .post-content-container {
        padding: 1.5rem;
        margin: 0 1rem;
    }
    
    h1 {
        font-size: 1.8rem;
    }
}


</style>